package com.lepu.app.widget;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.utils.BitmapLoadUtil;
import com.app.utils.DateUtil;
import com.app.utils.LoginUtil;
import com.app.utils.MyStoreUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.ui.auto_viewpager.AutoScrollViewPager;
import com.core.lib.ui.auto_viewpager.AutoScrollViewPagerAdapter;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.utils.main.UtilityBase;
import com.lepu.app.fun.health.activity.HealthWebActivity;
import com.lepu.app.fun.health.activity.MapActivity;
import com.lepu.app.fun.index.activity.IndexKnowActivity;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.main.bean.BeanFocus;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.pasm.R;

@SuppressLint("InflateParams")
public class FocusView extends LinearLayout implements AsyncRequest {

	public static final int TYPE_DEFAULT = 10;
	public static final int TYPE_STORE = 11;
	public static final int TYPE_INDEX_TOP = 12;

	private static final int INDEX_BANNER_SHOP_DEFAULT_COUNT = 4;

	private static final int INDEX_BANNER_INDEX_TOP_DEFAULT_COUNT = 1;

	private ArrayList<BeanFocus> mFocusList;

	public AutoScrollViewPager mAutoScrollViewPager;
	private AutoScrollViewPagerAdapter mPagerAdapter;
	private LinearLayout mFocusIndicator;
	private TextView mFocusName;

	private int mFocusPageCount;
	private BaseFragmentActivity mBaseFragmentActivity = null;
	private int mType = 0;
	SwipeRefreshLayout mGoogleRefreshLayout;

	public FocusView(Context context, ArrayList<BeanFocus> dataList, int type,SwipeRefreshLayout googleRefreshLayout) {
		super(context);

		mFocusList = dataList;
		mType = type;
		mBaseFragmentActivity = (BaseFragmentActivity) context;
		mGoogleRefreshLayout = googleRefreshLayout;

		LayoutInflater.from(mBaseFragmentActivity).inflate(
				R.layout.main_focus_view_acticle, this, true);
		init();
	}

	public FocusView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@SuppressLint("ClickableViewAccessibility")
	private void init() {

		FrameLayout contentLayout = (FrameLayout) findViewById(R.id.contentLayout);

		WindowManager wm = (WindowManager) mBaseFragmentActivity
				.getSystemService(Context.WINDOW_SERVICE);
		@SuppressWarnings("deprecation")
		int width = wm.getDefaultDisplay().getWidth();
		LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		params.width = width;
		params.height = width * 8 / 25;// width * 9 / 16;
		contentLayout.setLayoutParams(params);

		int count = 0;
		if (mFocusList != null && mFocusList.size() > 0) {

			if (mType == TYPE_STORE) {
				count = mFocusList.size() + INDEX_BANNER_SHOP_DEFAULT_COUNT;
			}else if (mType == TYPE_INDEX_TOP && checkIndexTopNeedDefault()) {
				count = mFocusList.size() + 1;
			} else {
				count = mFocusList.size();
			}
		}else{
			if (mType == TYPE_STORE) {
				count = INDEX_BANNER_SHOP_DEFAULT_COUNT;
			}else if (mType == TYPE_INDEX_TOP && checkIndexTopNeedDefault()) {
				count = INDEX_BANNER_INDEX_TOP_DEFAULT_COUNT;
			} else {
				count = 0;
			}
		}

		if(mType == TYPE_INDEX_TOP && checkIndexTopNeedDefault() && count == 1){
			contentLayout.addView(addIndexTop());
		}else if(count == 1 && mFocusList.size() > 0)
		{
			ImageView imageView = beanFocusClick(mFocusList.get(0));
			contentLayout.addView(imageView);
		}else if(count > 1){

			mAutoScrollViewPager = (AutoScrollViewPager) findViewById(R.id.autoScrollViewPager);
			mFocusIndicator = (LinearLayout) findViewById(R.id.focusIndicator);
			mFocusName = (TextView) findViewById(R.id.focusName);

			for (int i = 0; i < count; i++) {
				View v = new View(mBaseFragmentActivity);
				v.setBackgroundResource(R.drawable.app_point_bg);
				LayoutParams layoutParams = new LayoutParams(15, 15);
				layoutParams.setMargins(5, 5, 5, 5);
				mFocusIndicator.addView(v, layoutParams);
			}

			mPagerAdapter = new AutoScrollViewPagerAdapter(mBaseFragmentActivity) {

				@Override
				public List<View> buildViews() {
					return addView();
				}
			};

			mAutoScrollViewPager.setAdapter(mPagerAdapter);

			mFocusPageCount = count;

			mAutoScrollViewPager.setInterval(2000);
			mAutoScrollViewPager
					.setOnPageChangeListener(new MyOnPageChangeListener());
			mAutoScrollViewPager.setAutoScrollDurationFactor(10);
			mAutoScrollViewPager.start();

			if(mGoogleRefreshLayout != null)
			{
				mAutoScrollViewPager.setOnTouchListener(new OnTouchListener() {
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						switch (event.getAction()) {
							case MotionEvent.ACTION_MOVE:
								mGoogleRefreshLayout.setEnabled(false);
								break;
							case MotionEvent.ACTION_UP:
							case MotionEvent.ACTION_CANCEL:
								mGoogleRefreshLayout.setEnabled(true);
								break;
						}
						return false;
					}
				});
			}
		}
	}

	public void onResumeViewPager() {
		if (mAutoScrollViewPager != null) {
			mAutoScrollViewPager.onResume();
		}
	}

	public void onPauseViewPager() {
		if (mAutoScrollViewPager != null) {
			mAutoScrollViewPager.onPause();
		}
	}

	private boolean checkIndexTopNeedDefault()
	{
		boolean flag = false;

		if(LoginUtil.checkIsLogin())
		{
			String Instrument = MyApplication.getInstance().getLoginInfo().Instrument;
			if(!TextUtils.isEmpty(Instrument) && Instrument.equals("1"))
			{
				flag = true;
			}
		}
		return flag;
	}

	private List<View> addView() {

		List<View> list = new ArrayList<View>();

		if (mType == TYPE_STORE) {
			for(int i=0;i<INDEX_BANNER_SHOP_DEFAULT_COUNT;i++)
			{
				ImageView imageView = new ImageView(mBaseFragmentActivity);
				imageView.setLayoutParams(new ViewGroup.LayoutParams(
						ViewGroup.LayoutParams.MATCH_PARENT,
						ViewGroup.LayoutParams.MATCH_PARENT));
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);

				if(i == 0)
				{
					imageView.setBackgroundResource(R.drawable.index_mall_image);
					imageView.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							MyStoreUtil.getInstance().requestAllMarket(
									mBaseFragmentActivity, "");
						}
					});
				}else if(i == 1){
					imageView.setBackgroundResource(R.drawable.index_yuan_cheng_hui_zhen_image);
					imageView.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							//远程会诊
							UmengHelper.CustomEvent(mBaseFragmentActivity, UmengEvent.event_shouye_xunyiwenyao);

							Intent intent = new Intent(mBaseFragmentActivity, MapActivity.class);
							mBaseFragmentActivity.startActivity(intent,true);
						}
					});
				}else if(i == 2){
					imageView.setBackgroundResource(R.drawable.index_banner_pei_zhen);
					imageView.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							//陪诊
							UmengHelper.CustomEvent(mBaseFragmentActivity, UmengEvent.event_shouye_peizhenfuwu);

							Intent intent = new Intent(mBaseFragmentActivity, HealthWebActivity.class);
							intent.putExtra("url", Setting.getSuiXinZhenMainUrl());
							intent.putExtra("title", mBaseFragmentActivity.getString(R.string.health_title_pei_zhen));
							intent.putExtra("type", HealthWebActivity.TYPE_PEI_ZHEN);
							mBaseFragmentActivity.startActivity(intent, true);
						}
					});
				}else if(i == 3){
					imageView.setBackgroundResource(R.drawable.index_banner_zhuan_zhen);
					imageView.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							//转诊
							UmengHelper.CustomEvent(mBaseFragmentActivity, UmengEvent.event_shouye_zhuanzhenfuwu);

							Intent intentZhuanZhen = new Intent(mBaseFragmentActivity, HealthWebActivity.class);
							intentZhuanZhen.putExtra("url", Setting.getZhuanZhenMainUrl());
							intentZhuanZhen.putExtra("title", mBaseFragmentActivity.getString(R.string.health_title_zhuan_zhen));
							intentZhuanZhen.putExtra("type", HealthWebActivity.TYPE_ZHUAN_ZHEN);
							mBaseFragmentActivity.startActivity(intentZhuanZhen, true);
						}
					});
				}

				list.add(imageView);
			}
		}
		//首页 top
		else if(mType == TYPE_INDEX_TOP && checkIndexTopNeedDefault()){

			list.add(addIndexTop());
		}

		if (mFocusList != null && mFocusList.size() > 0) {
			for (int i = 0; i < mFocusList.size(); i++) {
				final BeanFocus item = mFocusList.get(i);
				ImageView imageView = beanFocusClick(item);
				list.add(imageView);
			}
		}

		return list;
	}

	private View addIndexTop()
	{
		View knowView = LayoutInflater.from(mBaseFragmentActivity).inflate(R.layout.index_top_know_view, null);
		TextView countText = (TextView) knowView.findViewById(R.id.count);
		TextView dateText = (TextView) knowView.findViewById(R.id.date);

		String surgicalTime = MyApplication.getInstance().getLoginInfo().SurgicalTime;

		countText.setText(DateUtil.getKnowThisDateCount(surgicalTime));
		dateText.setText(DateUtil.getKnowThisDateUnit(surgicalTime));

		knowView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

		knowView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				UmengHelper.CustomEvent(mBaseFragmentActivity,
						UmengEvent.event_shouye_shuhoutiantianzhi_banner);

				Intent intent = new Intent(mBaseFragmentActivity, IndexKnowActivity.class);
				mBaseFragmentActivity.startActivity(intent,true);
			}
		});
		return knowView;
	}

	private ImageView beanFocusClick(final BeanFocus item) {
		ImageView imageView = new ImageView(mBaseFragmentActivity);
		imageView.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		imageView.setScaleType(ImageView.ScaleType.FIT_XY);

		String imageUrl = item.Cover; // Setting.getImageUrl(item.Cover);
//				UniversalImageLoadTool.disPlayOrign(imageUrl, imageView,
//						R.drawable.default_icon_banner);
		BitmapLoadUtil.displayImage(R.drawable.default_icon_banner, imageUrl, imageView);

		imageView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				int type = UtilityBase.parseInt(item.LinkTargetType);
				Utils.jumpFocusPushClick(mBaseFragmentActivity, false,
						type, item.ArticleID, item.LinkURL,
						item.LinkTargetID, item.ViewCount,
						item.FavourCount,item.Cover,item.ArticleDescription);
			}
		});
		return imageView;
	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(int position) {

			try {
				int pos = position % mFocusPageCount;
				for (int i = 0; i < mFocusIndicator.getChildCount(); i++) {
					mFocusIndicator.getChildAt(i).setEnabled(false);
				}

				mFocusIndicator.getChildAt(pos).setEnabled(true);
				mFocusName.setVisibility(View.GONE);

				if (mType == TYPE_STORE) {
					if (pos >= INDEX_BANNER_SHOP_DEFAULT_COUNT) {
						mFocusName.setText(mFocusList.get(pos - INDEX_BANNER_SHOP_DEFAULT_COUNT).ACTitle);
					}
				}else if (mType == TYPE_INDEX_TOP && checkIndexTopNeedDefault()) {
					if (pos >= INDEX_BANNER_INDEX_TOP_DEFAULT_COUNT) {
						mFocusName.setText(mFocusList.get(pos - INDEX_BANNER_INDEX_TOP_DEFAULT_COUNT).ACTitle);
					}
				} else {
					mFocusName.setText(mFocusList.get(pos).ACTitle);
				}
			}catch (Exception e){
			}
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	@Override
	public void RequestComplete(Object object, Object data) {
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
	}
}
